package com.example.rabbitmq.config;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeoutException;

public class ConnectionConfig {
    private static final String USERNAME = "hkmq";
    private static final String PASSWORD = "hkmq";

    private static Logger logger = LoggerFactory.getLogger(ConnectionFactory.class);

    public void getConnection() throws IOException, TimeoutException {
        Connection connection = null;
        Channel channel = null;
        try {
            // 创建连接工厂
            ConnectionFactory connectionFactory = new ConnectionFactory();
            // 设置虚拟主机地址
            connectionFactory.setHost("192.168.0.246");
            // 设置段口号
            connectionFactory.setPort(5672);
            // 设置虚拟主机
            connectionFactory.setVirtualHost("hkgyl-mq");
            // 设置登陆帐号
            connectionFactory.setUsername(USERNAME);
            // 设置登陆密码
            connectionFactory.setPassword(PASSWORD);
            // 获取连接对象
            connection = connectionFactory.newConnection();
            // 创建连接通道
            channel = connection.createChannel();
        } finally {
            // 绑定队列
            bindQueue(channel);
            // 发布消息
            publishMsg(channel);
            // 关闭通道
            closeChannel(channel);
            // 关闭连接
            closeConnection(connection);
        }


    }

    /**
     * 绑定队列
     *
     * @param channel
     * @throws IOException
     */
    private String bindQueue(Channel channel) throws IOException {
        if (Objects.isNull(channel)) {
            return "bind queue failed, channel is null!";
        }
        // 参数1：队列名称；
        // 参数2：队列特性是否持久化；
        // 参数3：是否独占队列
        // 参数4：是否在消费完成后删除队列
        channel.queueDeclare("hello", false, false, false, null);
        return "bind queue success!";
    }

    /**
     * 发布消息
     *
     * @param channel
     */
    public String publishMsg(Channel channel) throws IOException {
        if (Objects.isNull(channel)) {
            return "publish message failed, channel is null!";
        }
        // 参数1：交换机
        // 参数2：队列名称
        // 参数3：消息额外设置
        // 参数4：消息内容
        channel.basicPublish("", "hello", null, "hello world".getBytes());
        return "publish message success!";
    }

    public String closeChannel(Channel channel) {
        if (Objects.nonNull(channel)) {
            try {
                channel.close();
            } catch (IOException | TimeoutException e) {
                logger.error("close channel failed, a reason is:{}", e.getMessage());
                return "close channel failed";
            }
        }
        return "close channel success!";
    }

    private String closeConnection(Connection connection) {
        if (Objects.nonNull(connection)) {
            try {
                connection.close();
            } catch (IOException e) {
                logger.error("close connection failed, a reason is:{}", e.getMessage());
                return "close connection failed";
            }

        }
        return "close connection success!";
    }

    public static void main(String[] args) throws IOException, TimeoutException {
        new ConnectionConfig().getConnection();
    }
}
